﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Text;

namespace ZX.WebApp.Extend
{
    public partial class hrEmpAddPhoto : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                string id = Request.QueryString["id"];

                this.Image1.ImageUrl = "hrEmpGetPhoto.aspx?id=" + id;
            }
        }

        /// <summary>
        /// 文件上传操作-单独隔离出来方法
        /// </summary>
        private string FileUploadCompant(FileUpload getfileupload)
        {
            string takeServerpath = string.Empty;//保存到服务器路径

            try
            {
                if (string.IsNullOrEmpty(getfileupload.PostedFile.FileName))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "aler ", "alert( '请选择上传文件的路径!'); ", true);
                    getfileupload.Focus();
                }
                else
                {
                    string filepath = getfileupload.PostedFile.FileName;//获得全路径
                    //获得文件名
                    string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);

                    //保存服务器路径 -唯一文件名
                    string serverpath = Server.MapPath("~/upload/hrEmployeePhotos/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + ".jpg";

                    //保存到服务器上
                    getfileupload.SaveAs(serverpath);

                    //返回图片的新名称
                    takeServerpath = serverpath;
                }
            }
            catch (Exception se)
            {
                //抓取一场信息 并提示
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "aler ", "alert( '文件上传失败-上传过程出现如下异常信息:" + se.Message.ToString() + "！'); ", true);
            }

            return takeServerpath;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // 路径
            string getfile = this.FileUpload1.PostedFile.FileName;
            //string getfile = Server.MapPath(this.FileUpload1.PostedFile.FileName);

            //#region 判断上传图片的格式re

            ////文件的后缀名
            string ImgExtend = getfile.Substring(getfile.LastIndexOf(".") + 1);

            if (ImgExtend.ToUpper() == "JPG" || ImgExtend.ToUpper() == "GIF" || ImgExtend.ToUpper().Equals("BMP") || ImgExtend.ToUpper() == "JPEG" || ImgExtend.ToUpper() == "PCX" || ImgExtend.ToUpper() == "TGA" || ImgExtend.ToUpper() == "PNG")
            { 
                //正确
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "aler ", "alert( '上传文件的格式不正确!'); ", true);
                return;
            }
            //#endregion
            //上传文件名
            string getlastpath = FileUploadCompant(this.FileUpload1);

            //创建文件流
            FileStream filestream = new FileStream(getlastpath, FileMode.Open);
            //获取上传文件流
            byte[] getbyte = new byte[filestream.Length];
            BinaryReader br = new BinaryReader(filestream);
            getbyte = br.ReadBytes(Convert.ToInt32(filestream.Length));

            filestream.Close();



            #region 插入数据

            StringBuilder sb = new StringBuilder();
            //修改该员工以前图片的状态
            sb.Append("update hrEmployeeFileStreams set Datstate = 1 where Precordid = @Precordid;");
            sb.Append("insert into hrEmployeeFileStreams(Precordid,CreatedBy, FileData, FileName, FileType) values(@Precordid,@CreatedBy, @FileData, @FileName, @FileType);");

            //打开数据库
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ToString();
            SqlConnection conn = new SqlConnection(connString);
            conn.Open();
            SqlCommand com = new SqlCommand(sb.ToString(), conn);

            com.Parameters.Add("Precordid", SqlDbType.UniqueIdentifier);
            com.Parameters["Precordid"].Value = Guid.Parse(Request.QueryString["id"].ToString());    //外键,员工
            com.Parameters.Add("CreatedBy", SqlDbType.VarChar, 50);
            com.Parameters["CreatedBy"].Value = (Session["User"] as ZX.EHR.Library.DatUser).UserID.ToString();    //创建人编号,datUse表
            com.Parameters.Add("FileData", SqlDbType.Image);
            com.Parameters["FileData"].Value = getbyte;     //文件流
            com.Parameters.Add("FileName", SqlDbType.Text);
            //获得文件名
            string filename = getlastpath.Substring(getlastpath.LastIndexOf("\\") + 1);
            com.Parameters["FileName"].Value = filename.Substring(0, filename.LastIndexOf("."));     //文件名
            com.Parameters.Add("FileType", SqlDbType.Text);
            com.Parameters["FileType"].Value = filename.Substring(filename.LastIndexOf(".") + 1);     // 文件流的类型【txt、jpg、rar】

            int ccc = com.ExecuteNonQuery();
            if (ccc > 0)
            {
                Random rd = new Random();
                this.Image1.ImageUrl = "hrEmpGetPhoto.aspx?id=" + Request.QueryString["id"]+"&rdn="+rd.Next(10000);
                //Response.Redirect=
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('添加成功');", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('添加失败');", true);
            }

            conn.Close();
            //filestream.Close();
            #endregion
        }
    }
}
